<template>
  <div class="account-man">
    <a-row justify="space-between" class="title-group">
      <a-col :span="8">
        <h3>详情列表</h3>
      </a-col>
      <a-col :span="8" offset="8" push="5">
        <a-button type="primary" icon="plus" @click="handleAddAccount"> 创建账号 </a-button>
        <util-modules @refresh="refreshData" @densityChange="densityChange" />
      </a-col>
    </a-row>
    <a-table
      @change="handleTableChange"
      :pagination="pagination"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data-source="data"
      :loading="isLoading"
      :size="activeSize"
    >
      <span slot="userType" slot-scope="_, record">
        <span v-if="record.userType == 1">媒体</span>
        <span v-if="record.userType == 2">广告主</span>
      </span>
      <span slot="username" slot-scope="_, record">
        <span>{{ record.username | filersText }}</span>
      </span>
      <span slot="balance" slot-scope="_, record">
        <span>{{ record.balance | filersTotal }}</span>
      </span>
      <span slot="userStatus" slot-scope="_, record">
        <span v-if="record.userStatus == 0">正常</span>
        <span v-if="record.userStatus == 1">停用</span>
      </span>
      <span slot="gmtCreate" slot-scope="_, record">
        <span>{{ record.gmtCreate | formatDate }}</span>
      </span>
      <span slot="action" slot-scope="_, record">
        <a @click="showModal(record)">设置</a>
        <a-divider type="vertical" />
        <template>
          <a v-if="record.userStatus == 0" @click="handleOpenOrStop(record.userStatus, record.id)">停用</a>
          <a v-if="record.userStatus == 1" @click="handleOpenOrStop(record.userStatus, record.id)">启用</a>
        </template>
        <template v-if="record.userType == 2">
          <a-divider type="vertical" />
          <a @click="handleTopup(record.id, record.username)">充值</a>
          <a-divider type="vertical" />
          <a @click="handleTopupRecord(record.id)">充值记录</a>
        </template>
      </span>
    </a-table>
    <my-modal
      v-if="modalVisible"
      :title="status === MODAL_TYPE.EDIT ? '编辑账号' : '新建账号'"
      :isMedia.sync="isMedia"
      :maskClosable="false"
      :visible="modalVisible"
      :modalLoading="modalLoading"
      :userTypeChange="userTypeChange"
      :echoData="echoData"
      :status="status"
      @forwardRef="handleRefForm"
      @cancel="handleClose"
      @submit="handleRecieve"
    />
    <!-- 充值 -->
    <a-modal
      title="充值"
      :dialog-style="{ top: '20px' }"
      :visible="topUpVisble"
      :maskClosable="false"
      @ok="handleTopUpVisbleOK"
      @cancel="handleTopUpVisbleCancel"
    >
      <a-form-item label="充值金额">
        <a-input-number v-model="fee" :min="0" placeholder="请输入名称" :defaultValue="0" style="width:50%" />
      </a-form-item>
    </a-modal>
    <!-- 充值 end -->
    <!-- 确定充值 -->
    <a-modal v-model="confirmTopUpVisvble" :maskClosable="false" title="确定充值">
      <template slot="footer">
        <a-button key="back" @click="handleCancelTopUp">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="confirmTopUploading" @click="handleConfirmTopUp">
          确定
        </a-button>
      </template>
      <p>
        是否为：{{ topUpData.username }} 充值 <span style="color:red;">￥{{ fee }}</span>
      </p>
    </a-modal>
    <!-- 确定充值 end -->
    <!-- 充值记录 -->
    <a-modal v-model="topUpRecordVisble" title="充值记录">
      <a-table :rowKey="(record) => record.id" :columns="columnsTopUp" :data-source="dataTopUp" :loading="isTopUpLoading">
        <span slot="gmtCreate" slot-scope="_, record">
          <span>{{ record.gmtCreate | formatDate }}</span>
        </span>
        <span slot="fee" slot-scope="_, record">
          <span>{{ record.fee | filersTotal }}</span>
        </span>
      </a-table>
      <template slot="footer">
        <a></a>
      </template>
    </a-modal>
    <!-- 充值记录 end-->
  </div>
</template>

<script>
import dayjs from 'dayjs'
import MyModal from './components/MyModal.vue'
import UtilModules from '_c/UtilModules.vue'
import { columns, columnsTopUp } from './account'
import { MODAL_TYPE } from '../../constant/index'
import { getTableSize } from '../../lib/utils'
import {
  getSubUserList,
  getSubUserOpen,
  getSubUserStop,
  postSubUserAdd,
  getSubUserBalanceOrder,
  getSubUserDeposit,
  postSubUserUpdate,
} from '@/api/accountMan/api'
export default {
  name: 'AccountMan',
  components: {
    MyModal,
    UtilModules,
  },
  data() {
    return {
      columns,
      columnsTopUp,
      activeSize: '',
      data: [],
      dataTopUp: [],
      MODAL_TYPE,
      isMedia: true,
      isLoading: false,
      isTopUpLoading: false,
      confirmTopUploading: false, //确认充值loading
      modalLoading: false,
      topUpVisble: false, // 充值
      topUpRecordVisble: false, // 充值记录
      confirmTopUpVisvble: false, // 确定充值
      modalVisible: false,
      topUpData: {}, //充值信息
      fee: 0, //充值金额
      echoData: {},
      status: MODAL_TYPE.ADD,
      refModalForm: null,
      pagination: {
        showSizeChanger: true, // 显示可改变每页数量
        defaultPageSize: 100,
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => `总共  ${total} 条`, // 显示总数
      },
    }
  },
  filters: {
    /**
     * @filter 处理数字
     */
    filersTotal(val) {
      return val == 0 ? '-' : (val / 10000).toFixed(2)
    },
    /**
     * @filter 处理文字
     */
    filersText(val) {
      return val == '' ? '-' : val
    },
    /**
     * @filter 格式化时间
     */
    formatDate(val) {
      return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.subUserList()
    })
  },
  methods: {
    /**
     * @func 刷新数据
     */
    refreshData() {
      this.subUserList()
    },
    /**
     * @func 表格密度
     */
    densityChange(value) {
      const { tableSize } = this.$store.state
      this.activeSize = getTableSize(value, tableSize)
    },
    /**
     * @func 表格改变时
     */
    async handleTableChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.subUserList({ pageNo: pagination.current, pageSize: pagination.pageSize })
    },
    handleRefForm(form) {
      this.refModalForm = form
    },
    /**
     * @func 查看充值记录
     */
    async subUserBalanceOrder(subUserId) {
      this.isTopUpLoading = true
      try {
        const data = await getSubUserBalanceOrder({ subUserId })
        if (data) {
          this.dataTopUp = data.list
          this.isTopUpLoading = false
        }
      } catch (err) {
        this.isTopUpLoading = false
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 充值金额
     */
    async subUserDeposit(param) {
      this.confirmTopUploading = true
      try {
        await getSubUserDeposit(param)
        this.$msgSuc('充值成功!')
        this.confirmTopUploading = false
        this.confirmTopUpVisvble = false
      } catch (err) {
        this.$msgErr(err.message)
        this.confirmTopUploading = false
      }
    },
    /**
     * @func 编辑账号更新
     */
    async subUserUpdate(param) {
      try {
        await postSubUserUpdate({ ...param })
        this.handleSubmitCustom()
        this.$msgSuc('更新成功!')
      } catch (err) {
        this.handleSubmitCustom()
        this.$msgErr(err.message)
      }
    },
    handleAddAccount() {
      this.status = MODAL_TYPE.ADD
      this.modalVisible = true
    },
    async subUserList(param) {
      this.isLoading = true
      const [err, data] = await getSubUserList({ ...param })
      if (!err) {
        const { list, count } = data
        const pager = { ...this.pagination }
        pager.total = count
        this.isLoading = false
        if (list) {
          this.data = list ?? []
        }
        this.pagination = pager
      } else {
        this.isLoading = false
        this.$msgErr(err)
      }
    },
    /**
     * @角色单选框切换
     * @param 1{媒体}
     * @param 2{广告主}
     */
    userTypeChange(e) {
      const { value } = e.target
      if (value == 2) {
        this.isMedia = false
      }
      if (value == 1) {
        this.isMedia = true
      }
    },
    /**
     * @显示模态框
     */
    showModal(record) {
      this.echoData = record
      this.status = MODAL_TYPE.EDIT
      // this.form.setFieldsValue(record)
      this.modalVisible = true
    },
    /**
     * @关闭模态框时
     */
    handleClose() {
      this.isMedia = true
      this.refModalForm = null
      this.modalVisible = false
    },
    /**
     * @启用或停止账号
     * @param id {0为停用, 1为启动}
     */
    handleOpenOrStop(status, id) {
      if (status == 0) {
        getSubUserStop({ id })
          .then(() => {
            this.subUserList()
          })
          .catch((err) => {
            this.$msgErr(err.msg)
          })
        this.$msgSuc('更新成功!')
      }
      if (status == 1) {
        getSubUserOpen({ id })
          .then(() => {
            this.subUserList()
          })
          .catch((err) => {
            this.$msgErr(err.msg)
          })
        this.$msgSuc('更新成功!')
      }
    },
    /**
     * @模态框表单数据提交
     */
    handleRecieve(values) {
      if (this.status == MODAL_TYPE.ADD) {
        this.submitProcessAdd(values)
      } else {
        this.submitProcessEdit(values)
      }
    },
    /**
     * @表单提交重复性步骤封装
     */
    handleSubmitCustom() {
      // this.form.resetFields()
      this.isMedia = true
      this.subUserList()
      this.modalLoading = false
      this.modalVisible = false
    },
    /**
     * @表单提交过程封装
     * @param 999997{关键字重复，请修改后重试}
     */
    submitProcessAdd(values) {
      this.modalLoading = true
      postSubUserAdd(values)
        .then((res) => {
          const { msg } = res.data
          this.modalLoading = false
          if (res.data.code == '999997') {
            this.handleSubmitCustom()
            this.$msgErr(`${msg}!`)
          } else {
            this.handleSubmitCustom()
            this.$msgSuc('添加成功!')
          }
        })
        .catch((err) => {
          this.$msgErr(err.message)
          this.modalLoading = false
        })
    },
    submitProcessEdit(values) {
      this.modalLoading = true
      this.subUserUpdate(values)
    },
    /**
     * @func 充值
     */
    handleTopup(subUserId, username) {
      this.topUpVisble = true
      this.topUpData = { subUserId, username }
    },
    /**
     * @func 充值记录
     */
    handleTopupRecord(subUserId) {
      this.subUserBalanceOrder(subUserId)
      this.topUpRecordVisble = true
    },
    /**
     * @func 充值确定
     */
    handleTopUpVisbleOK() {
      this.topUpVisble = false
      this.confirmTopUpVisvble = true
    },
    /**
     * @func 充值取消
     */
    handleTopUpVisbleCancel() {
      this.fee = 0
      this.topUpVisble = false
    },
    /**
     * @func 确认充值
     */
    handleConfirmTopUp() {
      const { subUserId } = this.topUpData
      const fee = this.fee * 10000
      if (fee > 0) {
        this.subUserDeposit({ subUserId, fee })
      } else {
        this.$msgSuc('充值成功!')
        this.confirmTopUploading = false
        this.confirmTopUpVisvble = false
      }
    },
    /**
     * @func 确认充值取消
     */
    handleCancelTopUp() {
      this.confirmTopUpVisvble = false
    },
  },
}
</script>

<style lang="scss" scoped>
.title-group {
  margin-bottom: 20px;
}
.ant-form-item {
  margin-bottom: 0;
}
</style>
